var Promise = require('../plugins/es6-promise.js');

function geturl(url){
    if (url.indexOf("http") <0){
        url =  getApp().globalData.url_local+url;
    }
    return url;
}

function json2Form(params) {

  var ap = getApp().globalData;

  // if (params.pageIndex == undefined ){
  //     params.pageSize=0;
  // }

  // if (params.pageSize == undefined ){
  //     params.pageSize = ap.defaultPageSize;
  // }

  if(ap.user != null){
    if (params.uid == undefined){
      params.uid = ap.user.uid;
    }

    if (params.unionId == undefined){
        params.unionId = ap.user.unionId;
    }

    if (params.openid == undefined){
      params.openid = ap.user.openid;
    }
  }

  var str = [];
  for (var p in params) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(params[p]));
  }
  return str.join("&");
}

function isOptStrNull(str){
    if(str == undefined || str == null || str == '' || str == 'null'||str == '[]'||str == '{}'){
        return true
    }else{
        return false;
    }
}

function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {

        //这里进行操作
        if(res.statusCode = 200){
          var responseData = res.data;

          var isSuccess = responseData.success;
          var msg = responseData.message;
          var data = responseData.data;
          var datacount = responseData.datacount;
          var rd={};


          if(isSuccess == undefined){
              reject(responseData);
              return;
          }

          if (isSuccess == true ) {

            resolve(data)

          } else {
             reject({message:msg});
          }
          
        }else{
          reject(res);
        }
      }
      obj.fail = function (res) {
        //失败
        reject(res)
      }
      fn(obj)
    })
  }
}

function wxPromisify2(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {

        //这里进行操作
        if(res.statusCode = 200){
          var responseData = res.data;

          var isSuccess = responseData.success;
          var msg = responseData.message;
          var data = responseData.data;
          var datacount = responseData.datacount;
          var rd={};


          if(isSuccess == undefined){
              reject(responseData);
              return;
          }

          if (isSuccess == true ) {

            resolve({data:data,count:datacount});

          } else {
             reject({message:msg});
          }
          
        }else{
          reject(res);
        }
      }
      obj.fail = function (res) {
        //失败
        reject(res)
      }
      fn(obj)
    })
  }
}


//无论promise对象最后状态如何都会执行
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};


/**
 * 微信请求get方法
 * url
 * data 以对象的格式传入
 */
function getRequest(url, data) {
  var getRequest = wxPromisify(wx.request)
  return getRequest({
    url: url,
    method: 'GET',
    data: data,
    header: {
      'Content-Type': 'application/json'
    }
  })
}

/**
 * 微信请求post方法封装
 * url
 * data 以对象的格式传入
 */
function postRequest(url, data) {
  var postRequest = wxPromisify(wx.request);

  data = json2Form(data);
  url = geturl(url);

  return postRequest({
    url: url,
    method: 'POST',
    data: data,
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
  });

}

function postRequest2(url, data) {
  var postRequest = wxPromisify2(wx.request);

  data = json2Form(data);
  url = geturl(url);

  return postRequest({
    url: url,
    method: 'POST',
    data: data,
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
  });

}

module.exports = {
  postRequest: postRequest,
  postRequest2: postRequest2,
  getRequest: getRequest
}